<template>
  <div class="orders">
    <h2 class="page-title">订单管理</h2>
    
    <!-- 搜索和筛选 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索商品名称"
        :prefix-icon="Search"
        style="width: 300px;"
        clearable
      />
      <el-select v-model="statusFilter" placeholder="订单状态" style="width: 150px;">
        <el-option label="全部" value="" />
        <el-option label="等待支付" :value="10" />
        <el-option label="已支付,待发货" :value="20" />
        <el-option label="已发货,待收货" :value="30" />
        <el-option label="交易成功" :value="40" />
        <el-option label="交易关闭" :value="50" />
      </el-select>
      <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
      <el-button :icon="Refresh" @click="handleReset">重置</el-button>
    </div>
    
    <!-- 订单列表 -->
    <div class="orders-table">
      <el-table :data="orders" style="width: 100%" v-loading="loading">
        <el-table-column prop="itemName" label="商品名称" />
        <el-table-column prop="totalAmount" label="订单总价">
          <template #default="scope">
            <span class="amount">¥{{ scope.row.totalAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="realPayAmount" label="实际支付金额">
          <template #default="scope">
            <span class="amount">¥{{ scope.row.realPayAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="postAmount" label="邮费">
          <template #default="scope">
            <span class="amount">¥{{ scope.row.postAmount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="payMethod" label="支付方式">
          <template #default="scope">
            {{ getPayMethodText(scope.row.payMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewOrder(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog
      v-model="showOrderDetail"
      title="订单详情"
      width="600px"
      :show-close="true"
      class="order-detail-dialog"
    >
      <div class="order-detail-content" v-loading="detailLoading">
        <div v-if="orderDetail" class="detail-info">
          <div class="detail-row">
            <span class="detail-label">订单ID：</span>
            <span class="detail-value">{{ orderDetail.id }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">用户ID：</span>
            <span class="detail-value">{{ orderDetail.userId }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">商品名称：</span>
            <span class="detail-value">{{ orderDetail.itemName }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">订单总价：</span>
            <span class="detail-value amount">¥{{ orderDetail.totalAmount }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">实际支付金额：</span>
            <span class="detail-value amount">¥{{ orderDetail.realPayAmount }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">邮费：</span>
            <span class="detail-value amount">¥{{ orderDetail.postAmount || 0 }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">支付方式：</span>
            <span class="detail-value">{{ getPayMethodText(orderDetail.payMethod) }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">订单状态：</span>
            <el-tag :type="getStatusType(orderDetail.status)">
              {{ getStatusText(orderDetail.status) }}
            </el-tag>
          </div>
          <div class="detail-row">
            <span class="detail-label">创建时间：</span>
            <span class="detail-value">{{ formatDateTime(orderDetail.createdTime) }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">创建用户ID：</span>
            <span class="detail-value">{{ orderDetail.createUserId }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">创建用户名：</span>
            <span class="detail-value">{{ orderDetail.createdUserName }}</span>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showOrderDetail = false">关闭</el-button>
          <el-button 
            v-if="orderDetail && orderDetail.status === 10" 
            type="primary" 
            @click="openPayDialog"
            class="pay-btn"
          >
            立即支付
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 支付弹窗 -->
    <el-dialog
      v-model="showPayDialog"
      title=""
      width="500px"
      :show-close="false"
      class="pay-dialog"
    >
      <div class="pay-dialog-content">
        <div class="pay-dialog-header">
          <div class="pay-crown">💳</div>
          <h2 class="pay-dialog-title">订单支付</h2>
          <p class="pay-dialog-subtitle">请选择支付方式完成订单支付</p>
        </div>
        
        <div class="payment-section">
          <h3 class="payment-title">选择支付方式</h3>
          <div class="payment-options">
            <label class="payment-option">
              <input
                type="radio"
                :value="2"
                v-model="selectedPayMethod"
                class="payment-radio"
              />
              <div class="payment-content">
                <img :src="alipayIcon" alt="支付宝" class="payment-icon" />
                <span class="payment-text">支付宝</span>
              </div>
              <div class="radio-indicator"></div>
            </label>
          </div>
        </div>
        
        <div class="pay-price-info" v-if="orderDetail">
          <div class="price-item">
            <span class="price-label">订单金额：</span>
            <span class="price-value">¥{{ orderDetail.totalAmount }}</span>
          </div>
          <div class="price-item">
            <span class="price-label">实际支付：</span>
            <span class="price-value amount">¥{{ orderDetail.realPayAmount }}</span>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="pay-dialog-footer">
          <el-button @click="closePayDialog" class="cancel-btn">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmPay"
            class="confirm-btn"
            :loading="payLoading"
          >
            {{ payLoading ? '处理中...' : '确认支付' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { searchOrders, getOrderDetail, payOrder } from '@/api/company'
import alipayIcon from '@/assets/images/controlPanel/alipay.png'

const loading = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const orders = ref([])

// 订单详情相关
const showOrderDetail = ref(false)
const detailLoading = ref(false)
const orderDetail = ref(null)

// 支付相关
const showPayDialog = ref(false)
const payLoading = ref(false)
const selectedPayMethod = ref(2) // 默认支付宝支付

// 获取订单数据
const fetchOrders = async () => {
  try {
    loading.value = true
    const params = {
      itemName: searchQuery.value || undefined,
      status: statusFilter.value || undefined,
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
    
    const response = await searchOrders(params)
    orders.value = response.list || []
    total.value = response.totals || 0
  } catch (error) {
    console.error('获取订单数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    10: 'warning',
    20: 'success',
    30: 'primary',
    40: 'success',
    50: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    10: '等待支付',
    20: '已支付,待发货',
    30: '已发货,待收货',
    40: '交易成功',
    50: '交易关闭'
  }
  return statusMap[status] || '未知'
}

// 获取支付方式文本
const getPayMethodText = (payMethod) => {
  const payMethodMap = {
    1: '微信',
    2: '支付宝'
  }
  return payMethodMap[payMethod] || '未知'
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'
  
  try {
    const date = new Date(dateTimeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    console.error('日期格式化失败:', error)
    return dateTimeStr
  }
}

// 查看订单详情
const viewOrder = async (order) => {
  try {
    detailLoading.value = true
    showOrderDetail.value = true
    
    const response = await getOrderDetail(order.id)
    orderDetail.value = response
    
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败，请稍后重试')
    showOrderDetail.value = false
  } finally {
    detailLoading.value = false
  }
}

// 打开支付弹窗
const openPayDialog = () => {
  showPayDialog.value = true
}

// 关闭支付弹窗
const closePayDialog = () => {
  showPayDialog.value = false
  payLoading.value = false
}

// 确认支付
const confirmPay = async () => {
  if (!orderDetail.value) return
  
  try {
    payLoading.value = true
    
    const response = await payOrder({
      orderId: orderDetail.value.id,
      payMethod: selectedPayMethod.value
    })
    
    console.log('支付响应结果:', response)
    
    // 创建一个临时的div来解析HTML
    const tempDiv = document.createElement('div')
    tempDiv.innerHTML = response
    
    // 查找表单元素
    const form = tempDiv.querySelector('form')
    if (form) {
      // 将表单添加到当前页面并自动提交
      document.body.appendChild(form)
      form.submit()
      
      // 关闭弹窗
      closePayDialog()
      showOrderDetail.value = false
      ElMessage.success('正在跳转到支付页面...')
      
      // 刷新订单列表
      fetchOrders()
    } else {
      throw new Error('未找到有效的支付表单')
    }
    
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败，请稍后重试')
  } finally {
    payLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchOrders()
}

// 重置
const handleReset = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  currentPage.value = 1
  fetchOrders()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchOrders()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchOrders()
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.orders {
  padding: 1rem;
}

.page-title {
  font-size: 1.6rem;
  color: #2d3748;
  margin-bottom: 2rem;
  font-weight: 500;
}

.search-bar {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid #e2e8f0;
  margin-bottom: 1.5rem;
  display: flex;
  gap: 1rem;
  align-items: center;
}

.orders-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid #e2e8f0;
  overflow: hidden;
}

.amount {
  font-weight: 600;
  color: #dc3545;
}

.pagination {
  padding: 1.5rem;
  display: flex;
  justify-content: center;
  border-top: 1px solid #e9ecef;
}

/* 订单详情弹窗样式 */
.order-detail-content {
  padding: 1rem 0;
}

.detail-info {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.detail-row {
  display: flex;
  align-items: center;
  padding: 0.75rem 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-row:last-child {
  border-bottom: none;
}

.detail-label {
  font-weight: 600;
  color: #2d3748;
  min-width: 120px;
  flex-shrink: 0;
}

.detail-value {
  color: #4a5568;
  flex: 1;
}

.detail-value.amount {
  font-weight: 600;
  color: #dc3545;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  padding: 1rem 0;
}

/* 弹窗标题样式 */
:deep(.order-detail-dialog .el-dialog__header) {
  background: linear-gradient(135deg, #e7bd77 0%, #d4a574 100%);
  color: white;
  padding: 1rem 1.5rem;
  margin: 0;
}

:deep(.order-detail-dialog .el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.order-detail-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 1.2rem;
}

:deep(.order-detail-dialog .el-dialog__headerbtn .el-dialog__close:hover) {
  color: #f0f0f0;
}

/* 支付弹窗样式 */
.pay-dialog-content {
  background: linear-gradient(135deg, #fff9ea 0%, #fef3e4 100%);
  padding: 32px;
  text-align: center;
}

.pay-dialog-header {
  margin-bottom: 32px;
}

.pay-crown {
  font-size: 48px;
  margin-bottom: 16px;
}

.pay-dialog-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 700;
  color: #2d3748;
  background: linear-gradient(135deg, #e7bd77 0%, #d4a574 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.pay-dialog-subtitle {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.payment-section {
  margin-bottom: 24px;
}

.payment-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
  text-align: left;
}

.payment-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.payment-option {
  position: relative;
  display: flex;
  align-items: center;
  padding: 16px;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #ffffff;
}

.payment-option:hover {
  border-color: #e7bd77;
  box-shadow: 0 4px 12px rgba(231, 189, 119, 0.2);
}

.payment-radio {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

.payment-radio:checked + .payment-content + .radio-indicator {
  background: #e7bd77;
  border-color: #e7bd77;
}

.payment-radio:checked + .payment-content + .radio-indicator::after {
  opacity: 1;
}

.payment-option:has(.payment-radio:checked) {
  border-color: #e7bd77;
  background: rgba(231, 189, 119, 0.05);
}

.payment-content {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.payment-icon {
  width: 32px;
  height: 32px;
  object-fit: contain;
}

.payment-text {
  font-size: 16px;
  font-weight: 500;
  color: #2d3748;
}

.radio-indicator {
  width: 20px;
  height: 20px;
  border: 2px solid #d1d5db;
  border-radius: 50%;
  position: relative;
  transition: all 0.3s ease;
  background: #ffffff;
}

.radio-indicator::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 8px;
  height: 8px;
  background: #ffffff;
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.pay-price-info {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid rgba(231, 189, 119, 0.3);
  margin-bottom: 20px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.price-item:last-child {
  margin-bottom: 0;
}

.price-label {
  font-size: 16px;
  color: #2d3748;
  font-weight: 500;
}

.price-value {
  font-size: 16px;
  color: #2d3748;
  font-weight: 500;
}

.price-value.amount {
  font-weight: 600;
  color: #dc3545;
}

.pay-dialog-footer {
  background: #ffffff;
  padding: 24px 32px;
  display: flex;
  justify-content: space-between;
  gap: 16px;
}

.pay-btn {
  background: linear-gradient(135deg, #e7bd77 0%, #d4a574 100%);
  border: none;
  font-weight: 600;
}

.pay-btn:hover {
  background: linear-gradient(135deg, #d4a574 0%, #c49669 100%);
}

/* 弹窗标题样式 */
:deep(.pay-dialog .el-dialog__header) {
  display: none;
}

:deep(.pay-dialog .el-dialog__body) {
  padding: 0;
}

:deep(.pay-dialog .el-dialog__footer) {
  padding: 0;
}
</style>
